package org.linlinjava.litemall.wx.service;

import org.aspectj.bridge.ILifecycleAware;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallAddressMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.CouponUserConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.BadAttributeValueExpException;
import javax.xml.ws.Response;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static org.linlinjava.litemall.wx.util.WxResponseCode.ORDER_INVALID;
import static org.linlinjava.litemall.wx.util.WxResponseCode.ORDER_UNKNOWN;

@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    LitemallAddressService addressService;

    @Autowired
    CartService cartService;

    @Autowired
    CouponVerifyService couponVerifyService;

    @Autowired
    LitemallOrderService orderService;

    @Autowired
    LitemallGoodsProductService goodsProductService;

    @Autowired
    LitemallCouponUserService couponUserService;

    @Autowired
    LitemallOrderGoodsService orderGoodsService;

    @Override
    @Transactional
    public Object submit(Integer userId, String body) {
        //判断用户是否登录
        if(userId == null || userId == 0){
            return ResponseUtil.unlogin();
        }

        if(body == null){
            return ResponseUtil.badArgumentValue();
        }

        //获取购物车id地址id消息 及其他信息
        Integer addressId = JacksonUtil.parseInteger(body,"addressId");
        Integer cartId = JacksonUtil.parseInteger(body,"cartId");
        Integer couponId =  JacksonUtil.parseInteger(body,"couponId");
        String message = JacksonUtil.parseString(body,"message");

        if(addressId == null || cartId == null || couponId ==null){
            return ResponseUtil.badArgumentValue();
        }

        //验证收货地址
        LitemallAddress checkedAddress = addressService.query(userId, addressId);
        if(checkedAddress == null){
            ResponseUtil.badArgumentValue();
        }


        List<LitemallCart> litemallCart = null;
        //判断购物车id
        if(cartId.equals(0)){
            //如果没有  获取根据id获取购物车
            litemallCart = cartService.showCart(userId);
        }else{
            litemallCart = new ArrayList<>();
            litemallCart.add(cartService.getLitemallCart(userId, cartId));
        }


        if(litemallCart.size() <= 0){
            return ResponseUtil.badArgumentValue();
        }
        //获取购物车金额
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        for (LitemallCart cart : litemallCart) {
            checkedGoodsPrice = cart.getPrice().multiply(new BigDecimal(cart.getNumber()));
        }

        //获取优惠券所减金额
        BigDecimal couponPrice = new BigDecimal(0.00);
        // 如果couponId=0则没有优惠券，couponId=-1则不使用优惠券
        if(couponId != 0 && couponId != -1){
            LitemallCoupon litemallCoupon = couponVerifyService.checkCoupon(userId, couponId, checkedGoodsPrice);
            if(litemallCoupon == null){
                return ResponseUtil.badArgumentValue();
            }
            couponPrice = litemallCoupon.getDiscount();
        }

        //根据订单商品总价计算运费满足条件（例如88元）则免运费，否则需要支付运费（例如8元）
        BigDecimal freightPrice = new BigDecimal(0.00);
        if(checkedGoodsPrice.compareTo(SystemConfig.getFreight()) > 0){
            freightPrice = SystemConfig.getFreight();
        }

        //订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

        //最终费用
        BigDecimal actualPrice = orderTotalPrice;

        LitemallOrder order = null;
        Integer orderId = null;

        order = new LitemallOrder();
        order.setUserId(userId);
        order.setOrderSn(getCurrentDateStr(userId));
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setConsignee(checkedAddress.getName());
        order.setMobile(checkedAddress.getTel());
        order.setMessage(message);
        String detailedAddress = checkedAddress.getProvince() + checkedAddress.getCity() + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
        order.setAddress(detailedAddress);
        order.setGoodsPrice(checkedGoodsPrice);
        order.setFreightPrice(freightPrice);
        order.setCouponPrice(couponPrice);
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(orderTotalPrice);
        order.setActualPrice(actualPrice);
        order.setGrouponPrice(new BigDecimal(0.00));
        //添加订单
        orderService.add(order);
        orderId = order.getId();

        //添加订单商品表
        for (LitemallCart cart : litemallCart) {
            //订单商品
            LitemallOrderGoods orderGoods = new LitemallOrderGoods();
            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoodsSn(cart.getGoodsSn());
            orderGoods.setProductId(cart.getProductId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setPicUrl(cart.getPicUrl());
            orderGoods.setPrice(cart.getPrice());
            orderGoods.setNumber(cart.getNumber());
            orderGoods.setSpecifications(cart.getSpecifications());
            orderGoods.setAddTime(new Date());

            orderGoodsService.add(orderGoods);
        }

        if(cartId.equals(0) || cartId == null){
            //删除购物车里面的商品信息
            cartService.deleteCartByUser(userId);
        }else{
            List<Integer> list = new ArrayList<>();
            list.add(cartId);
            cartService.deleteCart(cartId,list);
        }

        //减库存
        for (LitemallCart cart : litemallCart) {
            Integer productId = cart.getProductId();
            LitemallGoodsProduct product = goodsProductService.findProductById(productId);
            Integer remainNumber = product.getNumber() - cart.getNumber();
            if(product.getNumber() < 0){
                throw new RuntimeException("下单的商品货品数量大于库存量");
            }
            if(goodsProductService.reduceStock(productId,cart.getNumber()) <= 0){
                throw new RuntimeException("商品货品库存减少失败");
            }
            product.setNumber(product.getNumber() - cart.getNumber());

        }

        //如果使用了优惠券，设置优惠券使用状态
        if(couponId != 0 && cartId != -1){
            LitemallCouponUser couponUser = couponUserService.queryOne(userId, couponId);
            couponUser.setStatus(CouponUserConstant.STATUS_USED);
            couponUser.setUsedTime(new Date());
            couponUser.setOrderId(orderId);
            couponUserService.update(couponUser);
        }

        //返回订单id
        Map<String, Object> data = new HashMap<>();
        data.put("orderId", orderId);
        return ResponseUtil.ok(data);
    }

    @Override
    public Object detail(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        // 订单信息
        LitemallOrder order = orderService.findById(orderId);
        if (null == order) {
            return ResponseUtil.fail(ORDER_UNKNOWN, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(ORDER_INVALID, "不是当前用户的订单");
        }
        Map<String, Object> orderVo = new HashMap<String, Object>();
        orderVo.put("id", order.getId());
        orderVo.put("orderSn", order.getOrderSn());
        orderVo.put("addTime", order.getAddTime());
        orderVo.put("consignee", order.getConsignee());
        orderVo.put("mobile", order.getMobile());
        orderVo.put("address", order.getAddress());
        orderVo.put("goodsPrice", order.getGoodsPrice());
        orderVo.put("couponPrice", order.getCouponPrice());
        orderVo.put("freightPrice", order.getFreightPrice());
        orderVo.put("actualPrice", order.getActualPrice());
        orderVo.put("orderStatusText", OrderUtil.orderStatusText(order));
        orderVo.put("handleOption", OrderUtil.build(order));
        orderVo.put("expCode", order.getShipChannel());
        orderVo.put("expNo", order.getShipSn());

        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", orderVo);
        result.put("orderGoods", orderGoodsList);

        return ResponseUtil.ok(result);
    }

    private static String getCurrentDateStr(Integer userId){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("hhmmssSSS");
        return dateFormat.format(new Date())+userId;
    }

}
